const app = getApp()
import { info, save } from '../../../api/invoice'

Page({
  data: {
    theme: '',
    back: true,
    title: '发票信息',
    loading: true,
    submitLoading: false,
    form: {
      category: 0,
      title: '',
      tax_no: '',
      band_name: '',
      band_number: '',
      phone: '',
      email: ''
    }
  },
  onLoad (options) {
    this.setData({ loading: true, theme: app.global.theme })
    const form = this.data.form
    info().then(res => {
      if (res.data) {
        form.category = res.data.category == 10 ? 0 : 1
        form.title = res.data.title
        form.tax_no = res.data.tax_no
        form.band_name = res.data.band_name
        form.band_account = res.data.band_account
        form.phone = res.data.phone
        form.email = res.data.email
        this.setData({ form: form })
      }
    })
      .finally(() => {
        this.setData({ loading: false })
      })
  },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () { },

  // ===================methon================

  handleSubmit () {
    const form = this.data.form

    if (!form.title.trim()) {
      app.toast('请输入发票抬头名称')
      return false
    }
    if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(form.phone.trim())) {
      app.toast('请输入正确的手机号码')
      return false
    }

    if (form.category == 1) {
      if (!form.tax_no.trim()) {
        app.toast('请输入纳税人识别号')
        return false
      }
    }

    this.setData({ submitLoading: true })
    save(form).then(res => {
      wx.setStorageSync('invoice', 20)
      wx.navigateBack({
        delta: 1
      })
    })
      .catch(e => {
        app.toast(e.msg)
      })
      .finally(() => {
        this.setData({
          submitLoading: false
        })
      })
  },

  handleClear () {
    wx.setStorageSync('invoice', 10)
    wx.navigateBack({
      delta: 1
    })
  },

  onChange (event) {
    const form = this.data.form
    form.category = event.detail.index
    this.setData({
      form: form
    })
  },

  // ========================

  setPhone (event) {
    const form = this.data.form
    form.phone = event.detail
    this.setData({ form: form })
  },

  setEmail (event) {
    const form = this.data.form
    form.email = event.detail
    this.setData({ form: form })
  },

  setTelephone (event) {
    const form = this.data.form
    form.telephone = event.detail
    this.setData({ form: form })
  },

  setTitle (event) {
    const form = this.data.form
    form.title = event.detail
    this.setData({ form: form })
  },

  setTaxNo (event) {
    const form = this.data.form
    form.tax_no = event.detail
    this.setData({ form: form })
  },

  setBandName (event) {
    const form = this.data.form
    form.band_name = event.detail
    this.setData({ form: form })
  },

  setBandAccount (event) {
    const form = this.data.form
    form.band_account = event.detail
    this.setData({ form: form })
  }
})